package carts

import (
	"wuhuaguo.com/whg01/app/models"
	"wuhuaguo.com/whg01/app/models/products"
)

//管理用户的所有购物车信息

type cart struct {
	Userid int
	Items  []Product
}

func (c *cart) SumOfItems() int {
	sum := 0
	for i := 0; i < len(c.Items); i++ {
		sum += c.Items[i].Num
	}
	return sum
}

type Product struct {
	Itemid int
	Num    int
}

func (p Product) GetImtem() *models.Item {
	return products.GetImtem(p.Itemid)
}

func (ct *cart) addItem(itemid int) {
	//判断itemid 是否存在
	i := ct.findProduct(itemid)
	if i != -1 {
		ct.Items[i].Num += 1
	} else {
		p := Product{Itemid: itemid, Num: 1}
		ct.Items = append(ct.Items, p)
	}
}

//查询购物车中商品的位置 如果没有 －1
func (ct *cart) findProduct(itemid int) int {
	for i := 0; i < len(ct.Items); i++ {
		if ct.Items[i].Itemid == itemid {
			return i
		}
	}
	return -1
}

var (
	Carts_map map[int]*cart
)

func InitCartMap() {
	Carts_map = make(map[int]*cart)
}

func AddItemtoCart(userid int, itemid int) error {
	ct, exists := Carts_map[userid]
	if exists {
		ct.addItem(itemid)
		return nil
	} else {
		new_cart := &cart{Userid: userid}
		Carts_map[userid] = new_cart
		new_cart.addItem(itemid)
		return nil
	}
	return nil
}

func GetUserItemNum(userid int) int {
	ct, exists := Carts_map[userid]
	if exists {
		return ct.SumOfItems()
	} else {
		return 0
	}
}

func GetUserItems(userid int) []Product {
	ct, exists := Carts_map[userid]
	if exists {
		return ct.Items
	} else {
		return nil
	}
}
